import { useUserStore } from "@/store/useUserStore";
import axios, { AxiosError, type Method } from "axios";
import router from "@/app/routes/route";

const instance = axios.create({
  baseURL: "http://58.23.74.236:40001/",
  timeout: 30000,
});

instance.interceptors.request.use(
  function (config) {
    const { token } = useUserStore.getState();

    config.headers["Authorization"] = `${token}`;

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function (response) {
    // 注意，请求状态码!==业务状态码
    const { code, msg } = response.data;
    console.log("响应拦截器", code, msg);
    // 业务统一状态码出错
    if (code === 400 || code === 401 || code === 404) {
      console.log(msg || "请求出错, 请稍后再试");
      router.navigate("/login", {
        replace: true,
      });
      return;
    }

    console.log("响应拦截器", response.data);
    // 数据剥离
    return response.data;
  },
  function (error: AxiosError) {
    const { code } = error;
    const status = parseInt(code as string);
    console.log(error, "error", status);
    if (status === 401) {
      console.log("当前登录状态有误, 请重新登录");
      router.navigate("/login", {
        replace: true,
      });
    } else {
      // 其他请求状态码出错
      // message.error(`error: ${status}`)
    }
    return Promise.reject(error);
  }
);

export type Data<T> = {
  data: T;
  code: string | number;
  message: string | null;
};

/**
 * @param url 接口地址
 * @param method 请求方法(默认为GET)
 * @param submitData 请求数据(可选)
 * @returns
 */
export const request = <T>(
  url: string,
  method: Method = "GET",
  submitData?: object,
  options?: { signal?: AbortSignal }
) => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return instance.request<any, Data<T>>({
    url,
    method,
    [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
    signal: options?.signal,
  });
};
